package com.mf.morefun.ui.personnelmanagement;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.apkfuns.logutils.LogUtils;
import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.R;
import com.mf.morefun.adapter.PMUserAdapter;
import com.mf.morefun.base.BaseBusActivity;
import com.mf.morefun.bean.PMUserBean;
import com.mf.morefun.bean.PasswordBean;
import com.mf.morefun.bean.PersonPhoneBean;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.listener.ClassNumListen;
import com.mf.morefun.requestbean.RequestAddUserBean;
import com.mf.morefun.requestbean.RequestChangeUserBean;
import com.mf.morefun.requestbean.RequestEnableTImeBean;
import com.mf.morefun.requestbean.RequestPMBean;
import com.mf.morefun.requestbean.RequestPasswordBean;
import com.mf.morefun.requestbean.RequestPhoneBean;
import com.mf.morefun.requestbean.RequestSerchUserBean;
import com.mf.morefun.ui.person_detail.PersonDetailActivity;
import com.mf.morefun.ui.userinfo.LoginActivity;
import com.mf.morefun.util.GetUserInfo;
import com.mf.morefun.util.IsLoginBean;
import com.mf.morefun.widget.BackIdeaPop;
import com.mf.morefun.widget.NetErrorPop;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.DateUtils;
import com.zhcx.zhcxlibrary.utils.FileUtils;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.addapp.pickers.common.LineConfig;
import cn.addapp.pickers.picker.DatePicker;

public class PersonnelManagementActivity extends BaseBusActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.edit_serch)
    EditText editSerch;
    @BindView(R.id.tv_serch)
    TextView tvSerch;
    @BindView(R.id.iv_serch)
    ImageView ivSerch;
    @BindView(R.id.iv_add)
    ImageView ivAdd;
    @BindView(R.id.tv_learn)
    TextView tvLearn;
    @BindView(R.id.tv_lianxu)
    TextView tvLianxu;
    @BindView(R.id.tv_luyin)
    TextView tvLuyin;
    @BindView(R.id.tv_do)
    TextView tvDo;
    @BindView(R.id.lv_classnum)
    ListView lvClassnum;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.tv_timeenable)
    TextView tvTimeenable;
    @BindView(R.id.ll_enable)
    LinearLayout llEnable;
    @BindView(R.id.iv_student)
    ImageView ivStudent;
    @BindView(R.id.ll_student)
    LinearLayout llStudent;
    @BindView(R.id.iv_teacher)
    ImageView ivTeacher;
    @BindView(R.id.ll_teacher)
    LinearLayout llTeacher;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    @BindView(R.id.rl_bg)
    RelativeLayout rlBg;
    private List<PMUserBean> mPMUserList = new ArrayList<>();
    private List<PMUserBean> allUserList = new ArrayList<>();//保存一份接口所有数据
    private PMUserAdapter adapter;
    private int mYear = 2019;
    private int mMonth = 3;
    private int mDay = 18;
    private int selectEnableYear = 0;
    private int selectEnableMonth = 0;
    private int selectEnableDay = 0;
    private int selectYear = 0;
    private int selectMonth = 0;
    private int selectDay = 0;
    private SPUtils mSputils;

    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_personmanager;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mSputils = new SPUtils(PersonnelManagementActivity.this);
        if (!IsLoginBean.isNo(false)) {
            GetUserInfo.initLogin(mSputils.getString(Configuration.USERPHONE), mSputils.getString(Configuration.USERPASSWORD));
        }
        adapter = new PMUserAdapter(PersonnelManagementActivity.this, mPMUserList);
        lvClassnum.setAdapter(adapter);
        mYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date(System.currentTimeMillis())));
        mMonth = Integer.parseInt(new SimpleDateFormat("MM").format(new Date(System.currentTimeMillis())));
        mDay = Integer.parseInt(new SimpleDateFormat("dd").format(new Date(System.currentTimeMillis())));
        if (null != MoreFunApplication.loginBean.getResult().getOrgan()) {
            initGetAllUser();
        }
        rlBg.setVisibility(View.GONE);
        rlBg.getBackground().setAlpha(100);
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction("DELETEPERSON");
        mFilter.addAction("CHANGEPASSWORD");
        registerReceiver(mReceiver, mFilter);
        lvClassnum.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (null != mPMUserList && mPMUserList.size() > 0) {
                    if (StringUtils.isEmpty(mPMUserList.get(position).getUserType())) {
                        ToastUtils.show(getApplicationContext(), "未知类型", 100);
                    } else {
                        Intent mIntent = new Intent(PersonnelManagementActivity.this, PersonDetailActivity.class);
                        mIntent.putExtra("HeadPortrait", mPMUserList.get(position).getHeadPortrait());
                        mIntent.putExtra("Name", mPMUserList.get(position).getName());
                        if (null != mPMUserList.get(position).getUserFinance()){
                            mIntent.putExtra("Flows", mPMUserList.get(position).getUserFinance().getFlows() + "");
                            mIntent.putExtra("Stars", mPMUserList.get(position).getUserFinance().getStars() + "");
                            mIntent.putExtra("EnergyStones", mPMUserList.get(position).getUserFinance().getEnergyStones() + "");
                        }else {
                            mIntent.putExtra("Flows", "0");
                            mIntent.putExtra("Stars", "0");
                            mIntent.putExtra("EnergyStones", "0");
                        }
                        mIntent.putExtra("Phone", mPMUserList.get(position).getPhone());
                        mIntent.putExtra("Password", mPMUserList.get(position).getPassword());
                        mIntent.putExtra("Birthday", mPMUserList.get(position).getBirthday());
                        if (null != mPMUserList.get(position).getCity()){
                            mIntent.putExtra("City", mPMUserList.get(position).getCity().getName());
                        }else {
                            mIntent.putExtra("", "");
                        }
                        mIntent.putExtra("userId", mPMUserList.get(position).getId());
                        mIntent.putExtra("EnableEnd", mPMUserList.get(position).getEnableEnd());
                        mIntent.putExtra("Address", mPMUserList.get(position).getAddress());
                        mIntent.putExtra("UserType", mPMUserList.get(position).getUserType());
                        mIntent.putExtra("type", "2");
                        mIntent.putExtra("CLASSID", "1");
                        startActivity(mIntent);
                    }
                }
            }
        });
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("DELETEPERSON")) {
                initDeleteClassUser(mPMUserList, intent.getIntExtra("POSITION", 0));
            }else if(intent.getAction().equals("CHANGEPASSWORD")){
                initChangePassword(mPMUserList, intent.getIntExtra("POSITION", 0));
            }
        }
    };



    private void initGetAllUser() {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.QUERYALLUSER);
        RequestPMBean requestPMBean = new RequestPMBean();
        requestPMBean.setId(MoreFunApplication.loginBean.getResult().getOrgan().getId());
        params.setBodyContent(JSON.toJSONString(requestPMBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                mPMUserList.clear();
                LogUtils.d(result);
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(resultBean.getResult())) {
                            List<PMUserBean> pmUserBeanList = JSON.parseArray(resultBean.getResult(), PMUserBean.class);
                            mPMUserList.addAll(pmUserBeanList);
                            if (mPMUserList.size() > 0){
                                tvLearn.setText(mPMUserList.size() + "人");
                                //计算正常   过期

                                tvLianxu.setText(caluateNum(0) + "人");
                                tvLuyin.setText(caluateNum(1) + "人");
                            }else {
                                tvLearn.setText("0人");
                                tvLianxu.setText("0人");
                                tvLuyin.setText("0人");
                            }
                            adapter.setListen(new ClassNumListen() {
                                @Override
                                public void callBack(int position, TextView tvDo) {
                                    //
                                    try {
                                        showPop(mPMUserList, position, tvDo);
                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }

                                }
                            });
                        } else {
                            ToastUtils.show(getApplicationContext(), "数据为空", 100);
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private int caluateNum(int type){
        List<PMUserBean> mList = new ArrayList<>();
        try {
            for (int i = 0; i < mPMUserList.size(); i++){
                if (StringUtils.isEmpty(mPMUserList.get(i).getEnableEnd())) {
                    if (type == 1){
                        mList.add(mPMUserList.get(i));
                    }
                } else {
                    if (mPMUserList.get(i).getEnableEnd().length() == 10) {
                        long enableTime = DateUtils.DATE_YEAR_MONTH_DAY.parse(mPMUserList.get(i).getEnableEnd()).getTime() / 100000;
                        long currentTime = System.currentTimeMillis() / 100000;
                        if (enableTime > currentTime) {
                            if (type == 0){
                                mList.add(mPMUserList.get(i));
                            }
                        } else {
                            if (type == 1){
                                mList.add(mPMUserList.get(i));
                            }
                        }
                    } else {
                        long enableTime = DateUtils.DEFAULT_DATE_FORMAT.parse(mPMUserList.get(i).getEnableEnd()).getTime();
                        long currentTime = System.currentTimeMillis();
                        if (enableTime > currentTime) {
                            if (type == 0){
                                mList.add(mPMUserList.get(i));
                            }
                        } else {
                            if (type == 1){
                                mList.add(mPMUserList.get(i));
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mList.size();
    }

    private PopupWindow mDoPop;
    //弹出操作的弹框   需要三个按钮   设置有效期， 重置密码， 删除用户
    private void showPop(List<PMUserBean> pmUserBeanList, int position, TextView tvDo) {
        if (null == mDoPop) {
            View view = LayoutInflater.from(PersonnelManagementActivity.this).inflate(R.layout.layout_do, null);
            RelativeLayout rl_bg = view.findViewById(R.id.rl_bg);
            rl_bg.getBackground().setAlpha(100);
            TextView tv_user = view.findViewById(R.id.tv_user);
            tv_user.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mDoPop.dismiss();
                    mDoPop = null;
                    try {
                        showSelectType(tv_user, pmUserBeanList, position);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
            });
            TextView tv_timeenable = view.findViewById(R.id.tv_timeenable);
            tv_timeenable.setOnClickListener(new View.OnClickListener() {//设置有限期
                @Override
                public void onClick(View v) {
                    mDoPop.dismiss();
                    mDoPop = null;
                    showChangeTime(pmUserBeanList, position);
                }
            });
            TextView tv_changepassword = view.findViewById(R.id.tv_changepassword);
            tv_changepassword.setOnClickListener(new View.OnClickListener() {//重置密码
                @Override
                public void onClick(View v) {
                    mDoPop.dismiss();
                    mDoPop = null;
                    BackIdeaPop pops = new BackIdeaPop(PersonnelManagementActivity.this);
                    pops.showPop("确定要重置 " + pmUserBeanList.get(position).getName() + "的密码吗?", 11, position);
                }
            });
            TextView tv_deleteuser = view.findViewById(R.id.tv_deleteuser);
            tv_deleteuser.setOnClickListener(new View.OnClickListener() {//删除用户
                @Override
                public void onClick(View v) {
                    mDoPop.dismiss();
                    mDoPop = null;
                    //
                    BackIdeaPop pops = new BackIdeaPop(PersonnelManagementActivity.this);
                    pops.showPop("确定要删除 " + pmUserBeanList.get(position).getName() + "吗?", 5, position);
                }
            });
            TextView tvCancel = view.findViewById(R.id.tv_cancel);
            tvCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mDoPop.dismiss();
                    mDoPop = null;
                }
            });
            mDoPop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
            mDoPop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            mDoPop.setBackgroundDrawable(new BitmapDrawable());
            mDoPop.setFocusable(true);
            mDoPop.update();
            mDoPop.showAtLocation(view, Gravity.CENTER, 0, 0);
            mDoPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mDoPop.dismiss();
                    mDoPop = null;
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            unregisterReceiver(mReceiver);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void initDeleteClassUser(List<PMUserBean> pmUserBeanList, int position) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.DELETEUSER);
        RequestPMBean requestPMBean = new RequestPMBean();
        requestPMBean.setId(pmUserBeanList.get(position).getId());
        params.setBodyContent(JSON.toJSONString(requestPMBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        pmUserBeanList.remove(position);
                        adapter.notifyDataSetChanged();
                    } else {
                        ToastUtils.show(PersonnelManagementActivity.this, resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void initChangePassword(List<PMUserBean> pmUserBeanList, int position) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.CHANGEPASSWORD);
        RequestPasswordBean requestPasswordBean = new RequestPasswordBean();
        requestPasswordBean.setNewPassword(FileUtils.md5(pmUserBeanList.get(position).getPhone().substring(5)));
        requestPasswordBean.setPhone(pmUserBeanList.get(position).getPhone());
        params.setBodyContent(JSON.toJSONString(requestPasswordBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d(result);
                if (!StringUtils.isEmpty(result)) {
                    PasswordBean passwordBean = JSON.parseObject(result, PasswordBean.class);
                    ToastUtils.show(PersonnelManagementActivity.this, passwordBean.getMessage(), 100);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void showChangeTime(List<PMUserBean> pmUserBeanList, int position) {
        String enableEnd = pmUserBeanList.get(position).getEnableEnd();
        if (StringUtils.isEmpty(enableEnd)) {
            selectEnableYear = mYear;
            selectEnableMonth = mMonth;
            selectEnableDay = mDay;
        } else {
            String enable[] = enableEnd.split("-");
            try {
                if (enable.length == 3) {
                    selectEnableYear = Integer.parseInt(enable[0]);
                    selectEnableMonth = Integer.parseInt(enable[1]);
                    selectEnableDay = Integer.parseInt(enable[2]);
                } else {
                    selectEnableYear = mYear;
                    selectEnableMonth = mMonth;
                    selectEnableDay = mDay;
                }
            } catch (Exception e) {
                e.printStackTrace();
                selectEnableYear = mYear;
                selectEnableMonth = mMonth;
                selectEnableDay = mDay;
            }
        }
        DatePicker picker = new DatePicker(PersonnelManagementActivity.this, DatePicker.YEAR_MONTH_DAY);
        picker.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        picker.setRangeStart(1900, 1, 1);
        picker.setRangeEnd(2040, 12, 31);
        picker.setSelectedItem(selectEnableYear, selectEnableMonth, selectEnableDay);
        picker.setLineVisible(true);
        picker.setCanLoop(false);
        picker.setLineColor(0xfff0f0f0);
        picker.setTopPadding(10);
        picker.setSubmitTextColor(Color.parseColor("#00CC99"));
        picker.setSelectedTextColor(Color.parseColor("#333333"));
        LineConfig lineConfig = new LineConfig();
        lineConfig.setColor(Color.parseColor("#eaeaea"));
        picker.setLineConfig(lineConfig);
        picker.setCanLinkage(true);
        picker.setWeightEnable(true);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                String time = year + "-" + month + "-" + day;
                initChangeTime(time, pmUserBeanList, position);
            }
        });
        picker.show();
    }

    private void initChangeTime(String time, List<PMUserBean> pmUserBeanList, int position) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.SETTIMEENABLE);
        RequestEnableTImeBean requestEnableTImeBean = new RequestEnableTImeBean();
        requestEnableTImeBean.setEnableEnd(time);
        requestEnableTImeBean.setId(pmUserBeanList.get(position).getId());
        params.setBodyContent(JSON.toJSONString(requestEnableTImeBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        //这里说明修改成功了
                        pmUserBeanList.get(position).setEnableEnd(time);
                        adapter.notifyDataSetChanged();
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    @Override
    protected void initData() {
        editSerch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!StringUtils.isEmpty(s.toString())) {
                    if (null != MoreFunApplication.loginBean.getResult().getOrgan()) {
                        initSerchUser(s.toString());
                    }
                } else {
                    mPMUserList.clear();
                    mPMUserList.addAll(allUserList);
                    adapter.notifyDataSetChanged();
                    ToastUtils.show(getApplicationContext(), "请输入手机或昵称", 100);
                }
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.iv_add, R.id.tv_serch, R.id.iv_serch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_add://暂时没接口
                //先弹出手机的
                try {
                    showChangeName();
                }catch (Exception e){
                    e.printStackTrace();
                }

                break;
            case R.id.tv_serch://这里是代表取消
                editSerch.setVisibility(View.GONE);
                tvSerch.setVisibility(View.GONE);
                ivSerch.setVisibility(View.VISIBLE);
                mPMUserList.clear();
                mPMUserList.addAll(allUserList);
                adapter.notifyDataSetChanged();
                break;
            case R.id.iv_serch:
                allUserList.clear();
                allUserList.addAll(mPMUserList);
                editSerch.setVisibility(View.VISIBLE);
                tvSerch.setText("取消");
                tvSerch.setVisibility(View.VISIBLE);
                ivSerch.setVisibility(View.GONE);
                break;
        }
    }

    private PopupWindow mNamePop = null;

    //改名字
    private void showChangeName() {
        if (null == mNamePop) {
            LayoutInflater inflater = getLayoutInflater();
            View view = inflater.inflate(R.layout.layout_popphone, null);
            // 这里启动头像
            RelativeLayout rl_bg = view.findViewById(R.id.rl_bg);
            rl_bg.getBackground().setAlpha(100);
            EditText edit_name = view.findViewById(R.id.edit_name);
            edit_name.setHint("请输入您的手机号码");
            ImageView iv_cancel = view.findViewById(R.id.iv_cancel);
            iv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mNamePop.dismiss();
                    mNamePop = null;
                }
            });
            ImageView iv_sure = view.findViewById(R.id.iv_sure);
            iv_sure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (StringUtils.isEmpty(edit_name.getText().toString())) {
                        ToastUtils.show(PersonnelManagementActivity.this, "请输入手机号码", 100);
                        return;
                    }
                    if (edit_name.getText().toString().length() != 11 || !edit_name.getText().toString().substring(0, 1).equals("1")) {
                        ToastUtils.show(PersonnelManagementActivity.this, "请输入正确的手机号码", 100);
                        return;
                    }
                    mNamePop.dismiss();
                    mNamePop = null;
                    initIsRegister(edit_name.getText().toString());
                }
            });
            mNamePop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
            mNamePop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            mNamePop.setBackgroundDrawable(new BitmapDrawable());
            mNamePop.setFocusable(true);
            mNamePop.update();
            mNamePop.showAtLocation(view, Gravity.CENTER, 0, 0);
            mNamePop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mNamePop.dismiss();
                    mNamePop = null;
                }
            });
        }
    }

    private void initIsRegister(String phone) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.ISREGISTER);
        RequestPhoneBean requestPhoneBean = new RequestPhoneBean();
        requestPhoneBean.setPhone(phone);
        params.setBodyContent(JSON.toJSONString(requestPhoneBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(resultBean.getResult())) {
                            PersonPhoneBean mPerson = JSON.parseObject(resultBean.getResult(), PersonPhoneBean.class);
                            if (MoreFunApplication.loginBean.getResult().getOrgan().getId().equals(mPerson.getOrgan().getId())) {
                                showChangeUser(mPerson, phone);
                            } else {
                                ToastUtils.show(getApplicationContext(), "该用户不属于该机构", 100);
                            }
                        } else {
                            showChangeUser(null, phone);
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    //改名字
    private void showChangeUser(PersonPhoneBean mPerson, String phone) {
        rlBg.setVisibility(View.VISIBLE);
        editPhone.setText(phone);
        if (null != mPerson) {
            userType = 1;
            if (StringUtils.isEmpty(mPerson.getUserType())) {
                ivStudent.setImageResource(R.mipmap.xuanzhong);
                ivTeacher.setImageResource(R.mipmap.weixuanzhong);
            } else {
                if (mPerson.getUserType().equals("1")) {
                    ivStudent.setImageResource(R.mipmap.xuanzhong);
                    ivTeacher.setImageResource(R.mipmap.weixuanzhong);
                    userType = 1;
                } else {
                    ivStudent.setImageResource(R.mipmap.weixuanzhong);
                    ivTeacher.setImageResource(R.mipmap.xuanzhong);
                    userType = 2;
                }
            }
            if (StringUtils.isEmpty(mPerson.getEnableEnd())) {
                tvTimeenable.setText("");
            } else {
                tvTimeenable.setText(mPerson.getEnableEnd());
            }
        } else {
            userType = 1;
            ivStudent.setImageResource(R.mipmap.xuanzhong);
            ivTeacher.setImageResource(R.mipmap.weixuanzhong);
            tvTimeenable.setText("");
        }
        llTeacher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ivStudent.setImageResource(R.mipmap.weixuanzhong);
                ivTeacher.setImageResource(R.mipmap.xuanzhong);
                userType = 2;
            }
        });
        llStudent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ivStudent.setImageResource(R.mipmap.xuanzhong);
                ivTeacher.setImageResource(R.mipmap.weixuanzhong);
                userType = 1;
            }
        });
        if (StringUtils.isEmpty(tvTimeenable.getText().toString())) {
            selectYear = mYear;
            selectMonth = mMonth;
            selectDay = mDay;
        } else {
            String enable[] = tvTimeenable.getText().toString().split("-");
            try {
                if (enable.length == 3) {
                    selectYear = Integer.parseInt(enable[0]);
                    selectMonth = Integer.parseInt(enable[1]);
                    selectDay = Integer.parseInt(enable[2]);
                } else {
                    selectYear = mYear;
                    selectMonth = mMonth;
                    selectDay = mDay;
                }
            } catch (Exception e) {
                e.printStackTrace();
                selectYear = mYear;
                selectMonth = mMonth;
                selectDay = mDay;
            }
        }

        llEnable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePicker pickers = new DatePicker(PersonnelManagementActivity.this, DatePicker.YEAR_MONTH_DAY);
                pickers.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
                pickers.setRangeStart(1900, 1, 1);
                pickers.setRangeEnd(2040, 12, 31);
                pickers.setSelectedItem(selectYear, selectMonth, selectDay);
                pickers.setLineVisible(true);
                pickers.setCanLoop(false);
                pickers.setLineColor(0xfff0f0f0);
                pickers.setTopPadding(10);
                pickers.setSubmitTextColor(Color.parseColor("#00CC99"));
                pickers.setTopPadding(10);
                pickers.setSelectedTextColor(Color.parseColor("#333333"));
                LineConfig lineConfig = new LineConfig();
                lineConfig.setColor(Color.parseColor("#eaeaea"));
                pickers.setLineConfig(lineConfig);
                pickers.setCanLinkage(true);
                pickers.setWeightEnable(true);
                pickers.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                    @Override
                    public void onDatePicked(String year, String month, String day) {
                        String time = year + "-" + month + "-" + day;
                        tvTimeenable.setText(time);
                    }
                });
                pickers.show();
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rlBg.setVisibility(View.GONE);
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtils.isEmpty(tvTimeenable.getText().toString())) {
                    ToastUtils.show(PersonnelManagementActivity.this, "请选择有效期", 100);
                    return;
                }
                rlBg.setVisibility(View.GONE);
                if (null != MoreFunApplication.loginBean.getResult().getOrgan()) {
                    initAddUser(editPhone.getText().toString());
                }
            }
        });
    }

    private PopupWindow mUserPop;

    private void showSelectType(TextView tvTeache, List<PMUserBean> pmUserBeanList, int position) {
        userType = 1;
        if (null != pmUserBeanList && pmUserBeanList.size() > 0) {
            try {
                userType = Integer.parseInt(pmUserBeanList.get(position).getUserType());
            }catch (Exception e){
                e.printStackTrace();
                userType = 1;
            }
        }
        View view = LayoutInflater.from(PersonnelManagementActivity.this).inflate(R.layout.layout_popuser, null);
        TextView tvStudent = view.findViewById(R.id.tv_student);
        TextView tvTeacher = view.findViewById(R.id.tv_teacher);
        tvStudent.setTextSize(16);
        tvStudent.setTextColor(getResources().getColor(R.color.main_default_color));
        tvTeacher.setTextSize(14);
        tvTeacher.setTextColor(0xff666666);
        tvStudent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mUserPop.dismiss();
                tvStudent.setTextSize(16);
                tvStudent.setTextColor(getResources().getColor(R.color.main_default_color));
                tvTeacher.setTextSize(14);
                tvTeacher.setTextColor(0xff666666);
                userType = 1;
                if (null != pmUserBeanList && pmUserBeanList.size() > 0) {
                    initChangeUser(pmUserBeanList, position);
                } else {
                    tvTeache.setText("学员");
                }
            }
        });
        tvTeacher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mUserPop.dismiss();
                tvStudent.setTextSize(14);
                tvTeacher.setTextSize(16);
                tvStudent.setTextColor(0xff666666);
                tvTeacher.setTextColor(getResources().getColor(R.color.main_default_color));
                userType = 2;
                if (null != pmUserBeanList && pmUserBeanList.size() > 0) {
                    initChangeUser(pmUserBeanList, position);
                } else {
                    tvTeache.setText("老师");
                }
            }
        });
        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mUserPop.dismiss();
            }
        });
        mUserPop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        mUserPop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mUserPop.setBackgroundDrawable(new BitmapDrawable());
        mUserPop.setFocusable(true);
        mUserPop.update();
        mUserPop.showAtLocation(view, Gravity.CENTER, 0, 0);
        mUserPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mUserPop.dismiss();
                mUserPop = null;
            }
        });
    }

    private void initChangeUser(List<PMUserBean> pmUserBeanList, int position) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.CHANGEUSER);
        RequestChangeUserBean requestChangeUserBean = new RequestChangeUserBean();
        requestChangeUserBean.setId(pmUserBeanList.get(position).getId());
        requestChangeUserBean.setUserType(userType + "");
        params.setBodyContent(JSON.toJSONString(requestChangeUserBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        pmUserBeanList.get(position).setUserType(userType + "");
                        adapter.notifyDataSetChanged();
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private int userType = 1;

    private void initAddUser(String phone) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.REGISTER);
        RequestAddUserBean requestAddUserBean = new RequestAddUserBean();
        requestAddUserBean.setPhone(phone);
        requestAddUserBean.setPassword(FileUtils.md5(phone.substring(5)));
        requestAddUserBean.setUserType(userType + "");
        requestAddUserBean.setEnableEnd(tvTimeenable.getText().toString() + " 00:00:00");
        RequestAddUserBean.OrganBean organBean = new RequestAddUserBean.OrganBean();
        organBean.setId(MoreFunApplication.loginBean.getResult().getOrgan().getId());
        requestAddUserBean.setOrgan(organBean);
        params.setBodyContent(JSON.toJSONString(requestAddUserBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(resultBean.getResult())) {
                            PMUserBean pmUserBean = JSON.parseObject(resultBean.getResult(), PMUserBean.class);
                            if (null != pmUserBean.getOrgan()) {
                                if (StringUtils.isEmpty(pmUserBean.getOrgan().getId())) {
                                    ToastUtils.show(getApplicationContext(), "该用户不属于该机构", 100);
                                } else {
                                    if (MoreFunApplication.loginBean.getResult().getOrgan().getId().equals(pmUserBean.getOrgan().getId())) {
                                        mPMUserList.add(pmUserBean);
                                        adapter.notifyDataSetChanged();
                                    } else {
                                        ToastUtils.show(getApplicationContext(), "该用户不属于该机构", 100);
                                    }
                                }
                            } else {
                                ToastUtils.show(getApplicationContext(), "该用户不属于该机构", 100);
                            }
                        }
                    } else {
                        ToastUtils.show(PersonnelManagementActivity.this, resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(PersonnelManagementActivity.this);
                    errorPop.showPop("");
                    break;
            }
        }
    };

    private void initSerchUser(String info) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.SERCHUSER);
        RequestSerchUserBean requestSerchUserBean = new RequestSerchUserBean();
        requestSerchUserBean.setName(info);
        requestSerchUserBean.setPhone(info);
        RequestSerchUserBean.OrganBean organBean = new RequestSerchUserBean.OrganBean();
        organBean.setId(MoreFunApplication.loginBean.getResult().getOrgan().getId());
        requestSerchUserBean.setOrgan(organBean);
        params.setBodyContent(JSON.toJSONString(requestSerchUserBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d(result);
                mPMUserList.clear();
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(resultBean.getResult())) {
                            List<PMUserBean> pmUserBeanList = JSON.parseArray(resultBean.getResult(), PMUserBean.class);
                            mPMUserList.addAll(pmUserBeanList);
                        } else {
                            ToastUtils.show(getApplicationContext(), "数据为空", 100);
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private long isNum(String info) {
        long num = 0;
        try {
            num = Long.parseLong(info);
        } catch (Exception e) {
            e.printStackTrace();
            num = -1;
        }
        return num;
    }
}
